package com.own.business.selasticsearch.business.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.own.business.selasticsearch.business.entity.query.IndexManagementIndicesQuery;
import com.own.business.selasticsearch.business.entity.vo.IndexManagementIndicesVo;
import com.own.business.selasticsearch.business.service.ElasticsearchIndexManagementService;
import com.own.component.common.model.PageModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * ElasticsearchIndexManagementServiceImpl
 *
 * @author chenxueli
 * @date 2024-05-08 13:07:00
 */
@Slf4j
@Service
public class ElasticsearchIndexManagementServiceImpl implements ElasticsearchIndexManagementService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * 分页查询索引列表
     *
     * @param query 查询条件
     * @return PageModel<IndexManagementIndicesVo>
     */
    @Override
    public PageModel<IndexManagementIndicesVo> page(IndexManagementIndicesQuery query) {
        try {
            var response = elasticsearchClient.indices().stats();
            var stream = response.indices().entrySet()
                    .stream()
                    .filter(entry -> !entry.getKey().startsWith("."));
            if (StringUtils.isNotBlank(query.getKeywords())) {
                stream = stream.filter(entry -> entry.getKey().contains(query.getKeywords()));
            }
            var list = stream
                    .map(entry -> {
                        var index = entry.getKey();
                        return new IndexManagementIndicesVo(index, entry.getValue());
                    })
                    .sorted(Comparator.comparing(IndexManagementIndicesVo::getIndexName))
                    .collect(Collectors.toList());
            // 进行分页
            query.init();
            return new PageModel<>(list, query);
        } catch (Exception e) {
            throw new RuntimeException("查询索引列表失败", e);
        }
    }

}
